package com.mgg.auth.authentication.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author lijun
 * @Date: 2018-09-04 12:00:00
 */
@Component
public class MobileSecurityConfigure extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
	
	@Resource(name = "loginAuthenticationSuccessHandler")
	private AuthenticationSuccessHandler loginAuthenticationSuccessHandler;

	@Resource(name = "loginAuthenticationFailureHandler")
	private AuthenticationFailureHandler loginAuthenticationFailureHandler;
	
	@Autowired
	private MobileUserDetailService userDetailsService;

	@Override
	public void configure(HttpSecurity http) throws Exception {
		MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
		mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		mobileAuthenticationFilter.setAuthenticationSuccessHandler(loginAuthenticationSuccessHandler);
		mobileAuthenticationFilter.setAuthenticationFailureHandler(loginAuthenticationFailureHandler);

		MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
		mobileAuthenticationProvider.setUserDetailsService(userDetailsService);
		
		http.authenticationProvider(mobileAuthenticationProvider)
			.addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
	}
}
